package com.business.user.controller;

import cn.apiclub.captcha.Captcha;
import cn.apiclub.captcha.backgrounds.FlatColorBackgroundProducer;
import cn.apiclub.captcha.gimpy.RippleGimpyRenderer;
import com.business.common.utils.SystemClock;
import com.business.redis.ExpiresTimeEnum;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;

/**
 * 图片验证码
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaModuleController {

    private Logger logger = LoggerFactory.getLogger(CaptchaModuleController.class);

    private static int captchaW = 120;
    private static int captchaH = 50;

    @GetMapping(value = "/getCookie")
    public void getCookie(HttpServletResponse response) throws IOException {
        Cookie cookie = new Cookie("captchaToken", 0 + "");
        cookie.setPath("/");
        cookie.setMaxAge(5 * 60);
        response.addCookie(cookie);

    }

    @GetMapping(value = "/getCaptcha", produces = MediaType.IMAGE_PNG_VALUE)
    public void getCaptcha(@RequestParam("timestamp")String timestamp, HttpServletResponse response) {
        //生成验证码
        Captcha captcha = new Captcha.Builder(captchaW, captchaH)
                .addText().addBackground(new FlatColorBackgroundProducer(new Color(255, 180, 0)))
                .gimp(new RippleGimpyRenderer())
                .build();

        //生成一个token 返回前端 登陆时需要提交
        String key = String.format(RedisKeyConstant.USER_GET_CAPTCHA, timestamp);
        RedisUtil.setValue(key, captcha.getAnswer(), ExpiresTimeEnum.CAPTCHA.getExpiresTime());
        Cookie cookie = new Cookie("captchaToken", timestamp);
        cookie.setPath("/");
        cookie.setMaxAge(5 * 60);
        response.addCookie(cookie);
        try {
            ImageIO.write(captcha.getImage(), "png", response.getOutputStream());
        } catch (IOException e) {
            logger.error(e.getMessage(), e);

        }
    }
}

